package com.zqwh.xtool.api.offline;

import android.content.Context;

import com.zqwh.xtool.greendao.DaoManager;
import com.zqwh.xtool.greendao.DeviceDao;
import com.zqwh.xtool.greendao.db.Device;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

public class DeviceResposity {
    private DaoManager daoManager;
    private DeviceDao deviceDao;

    public DeviceResposity(Context context){
        daoManager = DaoManager.getInstance();
        daoManager.init(context);
        deviceDao = daoManager.getDaoSession().getDeviceDao();
    }

    /**
     * 插入记录
     *
     * @param device
     * @return
     */
    public boolean insertDevice(Device device) {
        return deviceDao.insertOrReplace(device) != -1;
    }
    /**
     * 插入多条记录
     * @param deviceList
     * @return
     */
    public boolean insertMultDevice(final List<Device> deviceList){
        boolean flag = false;
        try {
            daoManager.getDaoSession().runInTx(new Runnable() {
                @Override
                public void run() {
                    for (Device device : deviceList) {
                        deviceDao.insertOrReplace(device);
                    }
                }
            });
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 根据SN查询设备
     * @param sn
     * @return
     */
    public Device queryDeviceBySn(String sn){
        QueryBuilder<Device> qb = deviceDao.queryBuilder();
        qb.where(DeviceDao.Properties.Sn.eq(sn));
        return qb.unique();
    }
}
